<template>
  <div class="main ad-manage-edit">
    <el-form class="section" :model="formData" :rules="formRules" size="medium" ref="form" label-width="150px">
      <el-form-item label="所属广告位:" prop="aid">
        <el-select v-model="formData.aid" filterable clearable>
          <el-option v-for="item in positionList" :key="item.id" :label="item.positionName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="广告标题:" prop="adName">
        <el-input v-model="formData.adName"></el-input>
      </el-form-item>
      <el-form-item label="描述:" prop="desc">
        <el-input type="textarea" v-model="formData.desc"></el-input>
      </el-form-item>
      <el-form-item label="起止时间:" prop="dateTimeRange">
        <el-date-picker
          v-model="formData.dateTimeRange"
          type="datetimerange"
          range-separator="~"
          start-placeholder="开始时间"
          end-placeholder="结束时间">
        </el-date-picker>
      </el-form-item>
      <!-- 可以设置多图 -->
      <template v-if="dt_list">
        <el-form-item>
          <el-button type="primary" size="mini" @click="add_img()">添加图片</el-button>
        </el-form-item>
        <div class="mult-box">
          <div v-for="(ad_item,index) in formData.adMutiLinkList" :key="index" class="dt-box">
            <el-form-item :label="`广告图片${index+1}:`" :rules="formRules.image" :prop="'adMutiLinkList.'+index+'.image'" v-if="adType == 1 || adType == 2">
              <div class="im-up-box">
                <el-upload
                  class="avatar-uploader"
                  accept="image/*"
                  :action="upladUrl"
                  name="file"
                  :show-file-list="false"
                  :on-success="(response,file,fileList)=>dtUploadSuccess(response,file,fileList,ad_item)"
                  :before-upload="beforeUpload">
                  <img v-if="ad_item.image" :src="ad_item.image" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <div style="margin: -4px 20px 10px;">
                  <el-button type="danger" size="mini" @click="delete_dt(index)" plain>删除</el-button>
                </div>
              </div>
              <span class="upload-tip"><span>图片宽度750，高度不限</span></span>
            </el-form-item>
            <el-form-item label="广告小图:" :rules="formRules.littleImage" :prop="'adMutiLinkList.'+index+'.littleImage'" v-if="formData.aid === 38">
              <el-upload
                class="avatar-uploader"
                accept="image/*"
                :action="upladUrl"
                name="file"
                :show-file-list="false"
                :on-success="(response, file, fileList)=>dtUploadSuccessLittle(response,file,fileList,ad_item)"
                :before-upload="beforeUpload">
                <img v-if="ad_item.littleImage" :src="ad_item.littleImage" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="跳转类型:" :rules="formRules.jumpType" :prop="'adMutiLinkList.'+index+'.jumpType'">
              <el-radio v-for="(item, index) in jumpTypes" v-model="ad_item.jumpType" :label="item.val" :key="index">{{item.name}}</el-radio>
            </el-form-item>
            <el-form-item v-if="ad_item.jumpType === 2" label="跳转URL:" :prop="'adMutiLinkList.'+index+'.adLink'">
              <el-input v-model="ad_item.adLink" placeholder="http(s)://"></el-input>
            </el-form-item>
            <template v-else-if="ad_item.jumpType === 3">
              <el-form-item label="内页类型:" :prop="'adMutiLinkList.'+index+'.type'" :rules="formRules.type">
                <el-radio v-for="(item, index) in pageTypes" v-model="ad_item.type" :label="item.val" :key="index" @change="dtChangeType(item,ad_item)">{{item.name}}</el-radio>
              </el-form-item>
              <el-form-item v-if="ad_item.type === 1 || ad_item.type === 2 || ad_item.type === 5 || ad_item.type === 13 || ad_item.type === 88 || ad_item.type === 201"
              :label="`跳转${(pageTypes.filter(i => i.val ===ad_item.type)[0].name)}:`" :prop="'adMutiLinkList.'+index+'.jumpId'" :rules="formRules.jumpId">
                <span>{{ad_item.goodsName||ad_item.jumpId}}</span>
                <el-button type="primary" plain @click="dtChooseJump(ad_item)">请选择</el-button>
              </el-form-item>
              <el-form-item v-else-if="ad_item.type === 50 || ad_item.type === 51" label="小程序path:" :prop="'adMutiLinkList.'+index+'.jumpId'">
                <el-input v-model="ad_item.jumpId" placeholder="不填，默认小程序首页"></el-input>
              </el-form-item>
              <el-form-item v-else-if="ad_item.type === 14" label="URL:">
                <el-input v-model="ad_item.groupOilLink" placeholder="http(s)://"></el-input>
              </el-form-item>
            </template>
            <el-form-item label="跳转方式:" v-if="ad_item.type === 13&&ad_item.jumpId&&ad_item.jumpType===3">
              <el-radio v-model="ad_item.gotoWay" :label="0">直接跳转淘宝</el-radio>
              <el-radio v-model="ad_item.gotoWay" :label="1" :disabled="ad_item.radioDisabled">跳转活动中间页</el-radio>
            </el-form-item>
          </div>
        </div>
      </template>
      <!-- 不可设多图 -->
      <template v-else>
        <el-form-item label="广告图片:" prop="image" v-if="adType == 1 || adType == 2">
          <el-upload
            class="avatar-uploader"
            accept="image/*"
            :action="upladUrl"
            name="file"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload">
            <img v-if="formData.image" :src="formData.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <span class="upload-tip"><span>图片宽度750，高度不限</span><span v-show="formData.width&&formData.height">，当前：{{formData.width}}*{{formData.height}}</span></span>
        </el-form-item>
        <el-form-item label="广告小图:" prop="littleImage" v-if="formData.aid === 38">
          <el-upload
            class="avatar-uploader"
            accept="image/*"
            :action="upladUrl"
            name="file"
            :show-file-list="false"
            :on-success="uploadSuccessLittle"
            :before-upload="beforeUpload">
            <img v-if="formData.littleImage" :src="formData.littleImage" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="跳转类型:" prop="jumpType">
          <el-radio v-for="(item, index) in jumpTypes" v-model="formData.jumpType" :label="item.val" :key="index">{{item.name}}</el-radio>
        </el-form-item>
        <el-form-item v-if="formData.jumpType === 2" label="跳转URL:" prop="adLink" :rules="commonRules.ignoreInvite">
          <el-input v-model="formData.adLink" placeholder="http(s)://"></el-input>
        </el-form-item>
        <template v-else-if="formData.jumpType === 3">
          <el-form-item label="内页类型:" prop="type">
            <el-radio v-for="(item, index) in pageTypes" v-model="formData.type" :label="item.val" :key="index" @change="changeType(item)">{{item.name}}</el-radio>
          </el-form-item>
          <el-form-item v-if="showJumpBtn" :label="`跳转${(pageTypes.filter(i => i.val ===formData.type)[0].name)}:`" prop="jumpId" :rules="commonRules.notNullSelectRule">
            <span>{{formData.goodsName||formData.jumpId}}</span>
            <el-button type="primary" plain @click="chooseJump">请选择</el-button>
          </el-form-item>
          <el-form-item v-else-if="this.formData.type === 50 || this.formData.type === 51" label="小程序path:" prop="jumpId">
            <el-input v-model="formData.jumpId" placeholder="不填，默认小程序首页"></el-input>
          </el-form-item>
          <el-form-item v-else-if="formData.type === 14" label="URL:">
            <el-input v-model="formData.groupOilLink" placeholder="http(s)://"></el-input>
          </el-form-item>
        </template>
        <el-form-item label="跳转方式:" v-if="formData.type === 13&&formData.jumpId&&formData.jumpType===3">
          <el-radio v-model="formData.gotoWay" :label="0">直接跳转淘宝</el-radio>
          <el-radio v-model="formData.gotoWay" :label="1" :disabled="radioDisabled">跳转活动中间页</el-radio>
        </el-form-item>
      </template>
      <el-form-item v-if="formData.aid === 3" label="指定用户:" prop="useCondition">
        <el-radio  v-model="formData.useCondition" label="0" @change="changeValidate">不限制</el-radio><br/>
        <el-radio  v-model="formData.useCondition" label="1" @change="changeValidate">指定</el-radio>
        <template v-if="formData.useCondition==='1'">
          <div class="use-type-block" v-if="formData.aid===3">
            <el-checkbox v-model="formData['BY_USER_NEW']" :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'">用户类型：</el-checkbox>
            <el-checkbox-group :disabled="!formData['BY_USER_NEW'] || formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model="userType" @change="setUserType">
              <el-checkbox label="1" :key="1">新人用户</el-checkbox>
            </el-checkbox-group>
          </div>
          <div class="use-type-block">
            <!-- <span>用户等级：</span> -->
            <el-checkbox v-model="formData['BY_USER_TYPE']" :disabled="formData.activeState==='ACTIVITY_STATE_STOPPED'">用户等级：</el-checkbox>
            <el-checkbox-group :disabled="!formData['BY_USER_TYPE'] || formData.activeState==='ACTIVITY_STATE_STOPPED'" v-model="tempUserLevels" @change="setUserLevels">
              <el-checkbox label="0" :key="0">普通用户</el-checkbox>
              <el-checkbox label="1" :key="1">兰蜜</el-checkbox>
              <el-checkbox label="2" :key="2">大区</el-checkbox>
              <el-checkbox label="3" :key="3">董事</el-checkbox>
            </el-checkbox-group>
          </div>
        </template>
      </el-form-item>
      <el-form-item label="安卓显示:" prop="androidShowInfo.status">
        <el-radio v-model="formData.androidShowInfo.status" :label="1">全版本显示</el-radio>
        <el-radio v-model="formData.androidShowInfo.status" :label="2">全版本不显示</el-radio>
        <el-radio v-model="formData.androidShowInfo.status" :label="3">仅指定版本号显示</el-radio>
        <el-radio v-model="formData.androidShowInfo.status" :label="4">仅指定版本号不显示</el-radio>
      </el-form-item>
      <el-form-item v-if="formData.androidShowInfo.status > 2" label="安卓版本号:" prop="androidShowInfo.versionList" :rules="commonRules.notNullRule">
        <div class="version-add">
          <el-row>
            <el-col :span="5"><el-input type="number" v-model="androidVersion.first"></el-input></el-col>
            <el-col :span="1" align="center">.</el-col>
            <el-col :span="5"><el-input type="number" v-model="androidVersion.second"></el-input></el-col>
            <el-col :span="1" align="center">.</el-col>
            <el-col :span="5"><el-input type="number" v-model="androidVersion.third"></el-input></el-col>
            <el-col :span="7" align="center">
              <el-button type="primary" size="mini" @click="addVersion('android')">添加版本</el-button>
            </el-col>
          </el-row>
        </div>
        <div class="version-list">
          <el-tag v-for="(item, index) in formData.androidShowInfo.versionList" :key="index" effect="dark" closable @close="handleVersion('androidShowInfo', index)">{{item}}</el-tag>
        </div>
      </el-form-item>
      <el-form-item label="iOS显示:" prop="iosShowInfo.status">
        <el-radio v-model="formData.iosShowInfo.status" :label="1">全版本显示</el-radio>
        <el-radio v-model="formData.iosShowInfo.status" :label="2">全版本不显示</el-radio>
        <el-radio v-model="formData.iosShowInfo.status" :label="3">仅指定版本号显示</el-radio>
        <el-radio v-model="formData.iosShowInfo.status" :label="4">仅指定版本号不显示</el-radio>
      </el-form-item>
      <el-form-item v-if="formData.iosShowInfo.status > 2" label="iOS版本号:" prop="iosShowInfo.versionList" :rules="commonRules.notNullRule">
        <div class="version-add">
          <el-row>
            <el-col :span="5"><el-input type="number" v-model="iosVersion.first"></el-input></el-col>
            <el-col :span="1" align="center">.</el-col>
            <el-col :span="5"><el-input type="number" v-model="iosVersion.second"></el-input></el-col>
            <el-col :span="1" align="center">.</el-col>
            <el-col :span="5"><el-input type="number" v-model="iosVersion.third"></el-input></el-col>
            <el-col :span="7" align="center">
              <el-button type="primary" size="mini" @click="addVersion('ios')">添加版本</el-button>
            </el-col>
          </el-row>
        </div>
        <div class="version-list">
          <el-tag v-for="(item, index) in formData.iosShowInfo.versionList" :key="index" effect="dark" closable @close="handleVersion('iosShowInfo', index)">{{item}}</el-tag>
        </div>
      </el-form-item>
      <el-form-item label="h5显示:" prop="h5ShowInfo">
        <el-radio v-model="formData.h5ShowInfo" :label="1">显示</el-radio>
        <el-radio v-model="formData.h5ShowInfo" :label="2">不显示</el-radio>
      </el-form-item>
      <el-form-item label="小程序显示:" prop="miniAppShowInfo">
        <el-radio v-model="formData.miniAppShowInfo" :label="1">显示</el-radio>
        <el-radio v-model="formData.miniAppShowInfo" :label="2">不显示</el-radio>
      </el-form-item>
      <el-form-item label="是否启用:">
        <el-switch
          v-model="formData.status"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="是"
          inactive-text="否"
          :active-value="1"
          :inactive-value="0">
        </el-switch>
      </el-form-item>
      <el-form-item label="排序:">
        <el-input v-model="formData.sort" type="number"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="success" :loading="btnLoading" @click="save">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {regexp} from '../../../utils/tools'
import { tbActivityGet } from '@/api/bihuasuan/taobaoActivity'
export default {
  name: 'adManageEdit',
  props: {
    id: { default: '' }
  },
  data(){
    return {
      positionList: [],            // 广告位列表
      jumpTypes: [                 // 跳转类型
        { name: '无', val: 1},
        { name: 'URL', val: 2},
        { name: '内页', val: 3}
      ],
      pageTypes: [                 // 内页类型
        { name: '碧选商品', val: 1},
        { name: '碧划算商品', val: 88},
        { name: '套餐', val: 2},
        { name: '组合套餐', val: 201},
        { name: '活动', val: 5},
        { name: '箱起', val: 9},
        { name: '拼团', val: 10 },
        { name: '碧划算', val: 12},
        // { name: '碧选小程序', val: 50},
        { name: '碧选直播小程序', val: 51},
        { name: '淘宝官方活动', val: 13},
        { name: '团油', val: 14},
        { name: '今日热卖', val: 15},
        { name: '抽奖', val: 16},
      ],
      btnLoading: false,
      userType: [],
      userLevels: ['普通用户', '兰蜜', '大区', '董事'],
      tempUserLevels: [],
      androidVersion: {
        first: '',
        second: '',
        third: ''
      },
      iosVersion: {
        first: '',
        second: '',
        third: ''
      },
      formData: {
        height: null,
        width: null,
        groupOilLink: '',
        aid: '',
        adName: '',
        desc: '',
        dateTimeRange: [],
        startTime: '',
        endTime: '',
        image: '',
        littleImage: '',
        jumpType: 1,
        type: 1,
        useCondition: '0',
        adPermission: {
          newUser: false,
          roleIds: []
        },
        jumpId: '',
        goodsName: '',
        androidShowInfo: {
          status: 1,
          versionList: []
        },
        iosShowInfo: {
          status: 1,
          versionList: []
        },
        h5ShowInfo: 1,
        miniAppShowInfo: 1,
        status: 1,
        sort: '',
        gotoWay: 1,
        //多个图片跳转的情况，现在开通的aid:6广告通栏
        adMutiLinkList:[
          {
            jumpType: 1,
            adLink: "",
            jumpId: "",
            jumpTitle: "",
            image: "",
            type: 1,
            gotoWay: 1,
            groupOilLink: ""
          }
        ],
      },
      radioDisabled: false,
      formRules: {
        aid: [{ required: true, message: '请选择', trigger: 'change' }],
        adName: [
          {required: true, message: '不能为空', trigger: 'change'},
          {max: 100, message: '不能超过100字符', trigger: 'change'},
        ],
        dateTimeRange: [{ required: true, message: '不能为空', trigger: 'change' }],
        image: [{ required: true, message: '不能为空', trigger: 'change' }],
        littleImage: [{ required: true, message: '不能为空', trigger: 'change' }],
        // adCode: [{ required: true, message: '不能为空', trigger: 'change' }],
        adLink: [
          {required: true, message: '不能为空', trigger: 'change'},
          {pattern: regexp.url, message: '格式错误', trigger: 'change'}
        ],
        useCondition: [
          {required: true, message: '请选择指定类型', trigger: 'change'},
        ],
        jumpId:[
          { required: true, message: '请选择', trigger: 'change' },
        ]
      }
    }
  },
  computed: {
    isEdit() {
      return this.id && this.$route.name === 'adManageEdit';
    },
    adType() { // 广告类型
      let result = this.positionList.filter(item => item.id===this.formData.aid);
      if(result && result.length){
        return result[0].adType
      }
      return '';
    },
    showJumpBtn() {
      // 1：跳转碧选商品、2：跳转套餐、5：跳转活动、13淘宝官方活动、88：跳转碧划算商品、201：组合套餐
      return this.formData.type === 1 || this.formData.type === 2 || this.formData.type === 5 || this.formData.type === 13 || this.formData.type === 88 || this.formData.type === 201
    },
    //多广告图的aid,有增加的时候需要叫后端也增加
    dt_list(){
      return this.formData.aid===6||this.formData.aid===57||this.formData.aid===59
    }
  },
  created() {
    if (this.isEdit) {
      this.fetchData();
    }
    this.fetchAdPositionData();
  },
  methods: {
    //广告多图添加
    add_img(){
      if(!this.formData.adMutiLinkList){
        this.formData.adMutiLinkList=[];
      }
      if(this.formData.adMutiLinkList.length>=4){
        this.$message.error('最多添加4张图片');
        return;
      }
      this.formData.adMutiLinkList.push({
        jumpType: 1,
        adLink: "",
        jumpId: "",
        jumpTitle: "",
        image: "",
        type: 1,
        gotoWay: 1,
        groupOilLink: ""
      });
      console.log(this.formData.adMutiLinkList);
    },
    //广告多图删除
    delete_dt(index){
      this.formData.adMutiLinkList.splice(index, 1);
    },
    // 获取广告详情
    fetchData(){
      this.request({
        url: `/bsnl-ad/ad/${this.id}`,
        method: 'get'
      }).then(({data}) => {
        let result = {
          ...data,
          dateTimeRange: [data.startTime, data.endTime],
          gotoWay:data.gotoWay===1?1:0,
          width: data.width?data.width:null,
          height: data.height?data.height:null
        }
        // 首页下拉广告，有大图、小图都放在image字段，逗号(',')隔开
        if(data.aid === 38) {
          let images = result.image.split(',')
          if(images){
            result.image = images[0] || ''
            result.littleImage = images[1] || ''
          }
        }
        if(data.adPermission === null){
          result.useCondition = '0'
        } else {
          result.useCondition = '1'
          if(data.adPermission.newUser){
            result['BY_USER_NEW'] = true
            this.userType = ['1']
          }
          if(data.adPermission.roleIds){
            result['BY_USER_TYPE'] = true
            this.userType = ['1']
            result.adPermission.roleIds = data.adPermission.roleIds.map(i => i.toString())
            this.tempUserLevels = result.adPermission.roleIds
          }
        }
        this.formData = result;
        if(!this.formData.adMutiLinkList||this.formData.adMutiLinkList.length<=0){
          this.formData.adMutiLinkList=[];
          this.formData.adMutiLinkList.push({
            jumpType: 1,
            adLink: "",
            jumpId: "",
            jumpTitle: "",
            image: "",
            type: 1,
            gotoWay: 1,
            groupOilLink: ""
          });
        }
        if(data.type === 13) {
          tbActivityGet({id:result.jumpId}).then((res) =>{
            if(res.data.centerPage ===0) {
              this.radioDisabled = true
            } else {
              this.radioDisabled = false
            }
          })
        }

      }).catch(err => {
        console.log(err)
      })
    },
    // 获取所有广告位
    fetchAdPositionData(){
      this.request({
        url: '/bsnl-ad/adposition/list',
        method: 'get',
        params: {
          isPage: 1,
          pageIndex: 1,
          pageSize: 99999,
        }
      }).then(({data}) => {
        this.positionList = data ? data : []
      }).catch(err => {
        console.log(err)
        this.positionList = [];
      })
    },
    // 多广告图片上传
    dtUploadSuccess(response, file, fileList, ad_item){
      console.log(response, file, fileList, ad_item);
      let self = this;
      let image = new Image()
      image.src = response.filePath
      image.onload = function() {
        // self.$set(ad_item, 'width', image.width)
        // self.$set(ad_item, 'height', image.height)
      }
      this.$set(ad_item, 'image', this.replaceImgUrl(response.filePath))
    },
    // 广告图片上传
    uploadSuccess(response, file, fileList) {
      let self = this
      let image = new Image()
      image.src = response.filePath
      image.onload = function() {
        self.formData.width = image.width
        self.formData.height = image.height
      }
      this.$set(this.formData, 'image', this.replaceImgUrl(response.filePath))
    },
    // 多广告小图上传
    dtUploadSuccessLittle(response, file, fileList, ad_item){
      this.$set(ad_item, 'littleImage', this.replaceImgUrl(response.filePath));
    },
    // 广告小图上传
    uploadSuccessLittle(res) {
      this.$set(this.formData, 'littleImage', this.replaceImgUrl(res.filePath));
    },
    // 跳转选择
    chooseJump(){
      if(this.formData.type === 1){
        let checkData = [{
          id: this.formData.jumpId,
          name: this.formData.goodsName
        }];
        this.checkGoods(checkData, 1).then(val => {
          this.formData.jumpId = val[0].id;
          this.formData.goodsName = val[0].name;
        });
        return false;
      } else if(this.formData.type === 2){
        let checkData = [{
          packageId: this.formData.jumpId,
          name: this.formData.goodsName
        }];
        this.checkPackage(checkData, 1).then(val => {
          this.formData.jumpId = val[0].packageId;
          this.formData.goodsName = val[0].name;
        });
        return false;
      } else if(this.formData.type === 5){
        let checkData = [{
          id: this.formData.jumpId,
          name: this.formData.goodsName
        }];
        this.checkActivity(checkData, 1).then(val => {
          this.formData.jumpId = val[0].id;
          this.formData.goodsName = val[0].name;
        });
        return false;
      } else if(this.formData.type === 13) {
        let checkData = [{
          id: this.formData.jumpId,
          activityName: this.formData.goodsName,
          centerPage: this.formData.gotoWay===1?1:0,
        }];
        this.bhstaobaoActivity(checkData, 1).then(val => {
          this.formData.jumpId = val[0].id
          this.formData.goodsName = val[0].activityName
          this.formData.gotoWay = val[0].centerPage
          if(val[0].centerPage===0) {
            this.radioDisabled = true
          } else {
            this.radioDisabled = false
          }
        })
        return false
      } else if(this.formData.type === 88) {
        let checkData = [{
          goodsId: this.formData.jumpId,
          title: this.formData.goodsName
        }]
        this.bhsGoodsChoose(1, checkData, false).then(val => {
          // this.functionData.plateform = 'ALI'
          this.formData.jumpId = val[0].goodsId
          this.formData.goodsName = val[0].title
        })
        return false;
      } else if(this.formData.type === 201) {
        this.comboPackageChoose([], 1).then(val => {
          this.formData.jumpId = val[0].comboId;
          this.formData.goodsName = val[0].name;
        });
        return false;
      }
    },
    //多图情况下的跳转选择
    dtChooseJump(ad_item){
      if(ad_item.type === 1){
        let checkData = [{
          id: ad_item.jumpId,
          name: ad_item.goodsName
        }];
        this.checkGoods(checkData, 1).then(val => {
          ad_item.jumpId = val[0].id;
          ad_item.goodsName = val[0].name;
        });
        return false;
      } else if(ad_item.type === 2){
        let checkData = [{
          packageId: ad_item.jumpId,
          name: ad_item.goodsName
        }];
        this.checkPackage(checkData, 1).then(val => {
          ad_item.jumpId = val[0].packageId;
          ad_item.goodsName = val[0].name;
        });
        return false;
      } else if(ad_item.type === 5){
        let checkData = [{
          id: ad_item.jumpId,
          name: ad_item.goodsName
        }];
        this.checkActivity(checkData, 1).then(val => {
          ad_item.jumpId = val[0].id;
          ad_item.goodsName = val[0].name;
        });
        return false;
      } else if(ad_item.type === 13) {
        let checkData = [{
          id: ad_item.jumpId,
          activityName: ad_item.goodsName,
          centerPage: ad_item.gotoWay===1?1:0,
        }];
        this.bhstaobaoActivity(checkData, 1).then(val => {
          ad_item.jumpId = val[0].id
          ad_item.goodsName = val[0].activityName
          ad_item.gotoWay = val[0].centerPage
          if(val[0].centerPage===0) {
            ad_item.radioDisabled = true
          } else {
            ad_item.radioDisabled = false
          }
        })
        return false
      } else if(ad_item.type === 88) {
        let checkData = [{
          goodsId: ad_item.jumpId,
          title: ad_item.goodsName
        }]
        this.bhsGoodsChoose(1, checkData, false).then(val => {
          // this.functionData.plateform = 'ALI'
          ad_item.jumpId = val[0].goodsId
          ad_item.goodsName = val[0].title
        })
        return false;
      } else if(ad_item.type === 201) {
        this.comboPackageChoose([], 1).then(val => {
          ad_item.jumpId = val[0].comboId;
          ad_item.goodsName = val[0].name;
        });
        return false;
      }
    },
    setUserLevels() {
      if(this.formData.adPermission === '' || this.formData.adPermission === null ){
        this.formData.adPermission = Object.assign({}, {
          newUser: (this.userType.length>0),
          roleIds: Object.assign([], this.tempUserLevels)
        })
      } else {
        this.formData.adPermission.roleIds = Object.assign([], this.tempUserLevels)
      }
    },
    setUserType(val) {
      if(this.formData.adPermission === null ){
        this.formData.adPermission = Object.assign({}, {
          newUser: (this.userType.length>0),
          roleIds: Object.assign([], this.tempUserLevels)
        })
      }
      this.$refs.form.validateField('useCondition')
    },
    changeValidate(){
      this.$refs.form.clearValidate()
    },
    changeType(item){
      if(item.val ===9 || item.val === 10 || item.val === 12){
        this.formData.jumpId = item.val
      } else {
        this.$set(this.formData, 'jumpId', '')
        this.$set(this.formData, 'goodsName', '')
        this.$forceUpdate()
      }
    },
    dtChangeType(item, ad_item){
      if(item.val ===9 || item.val === 10 || item.val === 12){
        this.formData.jumpId = item.val
        ad_item.jumpId = item.val
      } else {
        this.$set(this.formData, 'jumpId', '')
        this.$set(this.formData, 'goodsName', '')
        this.$forceUpdate()
      }
    },
    // 添加版本
    addVersion(type) {
      const keyVersion = this[`${type}Version`]
      if(keyVersion.first!=='' && keyVersion.second!=='' && keyVersion.third!==''){
        let version = `${keyVersion.first}.${keyVersion.second}.${keyVersion.third}`
        if (this.formData[`${type}ShowInfo`].versionList.includes(version)){
          this.$message.warning('该版本已存在')
        } else {
          this.formData[`${type}ShowInfo`].versionList.push(version)
        }
      } else {
        this.$message.warning('请输入完整的版本号')
      }
    },
    // 删除版本号
    handleVersion(type, index) {
      this.formData[type].versionList.splice(index, 1)
    },
    save(){
      // 首页下拉广告，有大图、小图都放在image字段，逗号(',')隔开
      if(this.formData.aid === 38) {
        let images = `${this.formData.image},${this.formData.littleImage}`
        this.formData.image = images
      }
      // 如果置空了，则需要恢复
      if(this.formData.adPermission === null ) {
        let arr = {
          newUser: (this.userType.length > 0),
          roleIds: Object.assign([], this.tempUserLevels)
        }
        this.formData.adPermission = JSON.parse(JSON.stringify(arr))
      }
      // 如果未勾选
      if(this.formData.BY_USER_NEW == false) {
        this.userType.length = 0
      }
      if(this.formData.BY_USER_TYPE == false) {
        this.formData.adPermission.roleIds.length = 0
      }
      let condition = this.formData.useCondition
      // 判断指定用户项是否传空
      if(this.formData.useCondition === '0'){
        this.formData.adPermission = null
      } else if (this.formData.useCondition === '1') {
        if(this.userType.length > 0) {
          this.formData.adPermission.newUser = true
        }else {
          this.formData.adPermission.newUser = false
        }
        // 如果指定了，但是没选
        if(this.userType.length <= 0 && this.formData.adPermission.roleIds.length <= 0) {
          this.formData.useCondition = ''
        }

      }
      // 如果aid不是3或41（首页漂浮，vip会员(去除了)），adPermission一律为null
      if(this.formData.aid !== 3) {
        this.formData.adPermission = null
      }

      if(this.formData.adPermission !== null) {
        if(this.formData.adPermission.roleIds !== null){
          this.formData.adPermission.roleIds = this.formData.adPermission.roleIds.map(item => Number(item))
        }
      }

      this.$refs.form.validate(valid => {
        if (!valid) {
          this.formData.useCondition = condition
          return false;
        }
        //多广告图的情况
        if(this.dt_list){
          if(!this.formData.adMutiLinkList||this.formData.adMutiLinkList.length<=0){
            this.$message.error('请至少添加一张图片');
            return;
          }
          //图片取第一个
          this.$set(this.formData, 'image', this.formData.adMutiLinkList[0].image);//为了list能显示，取第一个图片
        }
        let dateTimeRange = this.formData.dateTimeRange;
        if (dateTimeRange && dateTimeRange.length > 0) {
          this.formData.startTime = dateTimeRange[0];
          this.formData.endTime = dateTimeRange[1];
        }
        if(this.isEdit){
          // 如果是编辑
          this.request({
            url: '/bsnl-ad/ad/'+this.$route.params.id,
            method: 'put',
            data: this.formData
          }).then(() => {
            this.$message.success('编辑广告成功');
            this.$router.push({name: 'adManage'});
            return false;
          }).catch(err => {
            console.error(err);
          });
        } else {
          // 如果是新增
          this.request({
            url: '/bsnl-ad/ad/',
            method: 'post',
            data: this.formData
          }).then(() => {
            this.$message.success('新建广告成功');
            this.$router.push({name: 'adManage'});
          }).catch(err => {
            console.error(err);
          });
        }

      });
    }
  }
}
</script>
<style lang="scss" scoped>
  @import "../../../styles/_mixin.scss";
  .upload-tip {
    color: red;
  }
  .use-type-block{
    @include flex;
    margin-left: 24px;
  }
  .el-checkbox {
    margin-right: 15px;
  }
  .version-list{
    margin-top: 10px;
    min-height: 100px;
    padding: 0 10px;
    background: #f2f2f2;
  }
  .version-add{
    width: 400px;
  }
  .el-input{
    width: 100%;
    max-width: 500px;
  }
  .el-tag{
    margin-right: 12px;
  }
  // .mult-box{
  //   margin: 10px 0rpx;
  // }
  .dt-box{
    border-bottom: 1px solid #EEEEEE;
    margin-bottom: 25px;
  }
  .im-up-box{
    display: flex;
  }
</style>
